package com.example.makerspace.schedule;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.makerspace.domain.TaskDO;
import com.example.makerspace.domain.TaskStatusDO;
import com.example.makerspace.enums.maker.StatusInEnum;
import com.example.makerspace.mapper.TaskMapper;
import com.example.makerspace.mapper.TaskStatusMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Component
public class TaskSchedule {
    @Autowired
    private TaskMapper taskMapper;
    @Autowired
    private TaskStatusMapper taskStatusMapper;

    @PostConstruct
    public void startTaskStatusHandle() {
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        // 设定任务，这里以每隔一定时间打印一条信息为例
        Runnable task = () -> {
            try {
                System.out.println("开始执行定制任务");
                List<TaskDO> taskDOS = taskMapper.selectList(null);
                for (TaskDO taskDO : taskDOS) {
                    List<TaskStatusDO> taskStatusDOS = taskStatusMapper.selectList(new QueryWrapper<TaskStatusDO>().eq("task_id", taskDO.getId()));
                    // 在这里编写你的定时任务逻辑
                    taskStatusDOS.sort(Comparator.comparing(TaskStatusDO::getStatusId));
                    //计算当前所处阶段
                    LocalDateTime now = LocalDateTime.now();
                    LocalDateTime date = LocalDateTime.ofInstant(taskDO.getCreateTime().toInstant(), ZoneId.systemDefault());

                    Integer nowStatus = StatusInEnum.COMPLETED.getStatusId();
                    Long remainder = null;
                    for (TaskStatusDO taskStatusDO : taskStatusDOS) {
                        date = date.plusDays(taskStatusDO.getDelay()).plusDays(taskStatusDO.getDuration());
                        int res = now.compareTo(date);
                        if (res < 0) { //所处当前阶段
                            nowStatus = taskStatusDO.getStatusId();
                            // 计算两个LocalDateTime之间的时间差
                            Duration duration = Duration.between(now, date);

                            // 获取分钟数
                            remainder = duration.toMinutes();
                            break;
                        }
                    }
                    if (nowStatus.equals(StatusInEnum.COMPLETED.getStatusId())) {
                        remainder = null;
                    }
                    taskDO.setStatusId(nowStatus);
                    taskDO.setRemainder(remainder == null ? null : remainder.intValue());
                    taskMapper.updateById(taskDO);
                }
                System.out.println("结束执行定制任务");
            } catch (Exception e) {
                // 如果任务发生异常，则将异常信息打印出来并抛出
                e.printStackTrace();
                System.out.println("错误信息"+ e.getMessage());
                throw new RuntimeException("定时任务执行失败：" + e.getMessage());
            }
        };

        // 设定任务的执行周期和时间单位，这里设定为每隔5秒执行一次
        int initialDelay = 0; // 初始延迟
        int period = 60; // 执行周期
        TimeUnit timeUnit = TimeUnit.SECONDS; // 时间单位

        // 执行定时任务
        scheduler.scheduleAtFixedRate(task, initialDelay, period, timeUnit);
    }
}
